﻿/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    //合并两个有序数组
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
    {
        if (list1 && !list2)
        {
            return list1;
        }
        if (!list1 && list2)
        {
            return list2;
        }
        ListNode* head = nullptr, * cur = nullptr;
        ListNode* p1 = list1, * p2 = list2;
        while (p1 && p2)
        {
            if (p1->val < p2->val)
            {
                if (!head)
                {
                    head = p1;
                    cur = p1;
                }
                else
                {
                    cur->next = p1;
                    cur = cur->next;
                }
                p1 = p1->next;
            }
            else
            {
                if (!head)
                {
                    head = p2;
                    cur = p2;
                }
                else
                {
                    cur->next = p2;
                    cur = cur->next;
                }
                p2 = p2->next;
            }
        }
        while (p1)
        {
            cur->next = p1;
            cur = cur->next;
            p1 = p1->next;
        }
        while (p2)
        {
            cur->next = p2;
            cur = cur->next;
            p2 = p2->next;
        }
        return head;
    }
    ListNode* sortList(ListNode* head)
    {
        if (!head)
            return head;
        if (!head->next)
            return head;
        ListNode* fast = head, * slow = head;
        while (fast->next != nullptr && fast->next->next != nullptr)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* list1 = head;
        ListNode* list2 = slow->next;
        slow->next = nullptr;
        return mergeTwoLists(sortList(list1), sortList(list2));
    }
};